package com.qiezikaka.kaka.ui.detail;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.makeramen.roundedimageview.RoundedImageView;
import com.manitozhang.CircleProgress;
import com.qiezikaka.kaka.R;
import com.qiezikaka.kaka.adapter.DialogBackAdapter;
import com.qiezikaka.kaka.adapter.FengGeSceneAdapter;
import com.qiezikaka.kaka.adapter.FuZhuangDataListAdapter;
import com.qiezikaka.kaka.base.BaseActivity;
import com.qiezikaka.kaka.bean.PythonResponInfo;
import com.qiezikaka.kaka.bean.QcodeInfo;
import com.qiezikaka.kaka.bean.SiteDetailInfo;
import com.qiezikaka.kaka.bean.SiteSceneShowInfo;
import com.qiezikaka.kaka.bean.UploadImgInfo;
import com.qiezikaka.kaka.common.Common;
import com.qiezikaka.kaka.databinding.ActivityTakleCameraFaceDetailBinding;
import com.qiezikaka.kaka.http.HttpClient;
import com.qiezikaka.kaka.net.http.HttpUrl;
import com.qiezikaka.kaka.ui.scan.ScanCodeActivity;
import com.qiezikaka.kaka.view.CircleViewOutlineProvider;
import com.qiezikaka.kaka.view.GPUImageMirrorFilter;
import com.qiezikaka.kaka.view.GridSpacingItemDecoration;
import com.qiezikaka.kaka.view.v1.GPUImageBeautyFilter;
import com.qiezikaka.kaka.view.v1.Util;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import jp.co.cyberagent.android.gpuimage.GPUImage;
import jp.co.cyberagent.android.gpuimage.GPUImageFilterGroup;

public class DetailCameraFaceTakleActivity extends BaseActivity<DetailPresenter> implements DetailContract.View, View.OnClickListener {
    private ActivityTakleCameraFaceDetailBinding detailBinding;
    private DetailPresenter presenter;
    private String pid;
    private String[] mPermissions = {Manifest.permission.CAMERA};
    private static final int PERMISSION_REQUEST_CODE = 10;
    private boolean hasPermissions;
    private boolean resume = false;//解决home键黑屏问题
    private File uploadFile;
    private boolean isPreviewing;
    private int currentCameraId;
    private GPUImage gpuImage;
    private GPUImageFilterGroup magicFilterGroup;
    private GPUImageFilterGroup noMagicFilterGroup;
    private Camera camera;
    private static final int PICTURE_WIDTH = 1280;
    private static final int PICTURE_HEIGHT = 720;
    private static final int PREVIEW_WIDTH = 1280;
    private static final int PREVIEW_HEIGHT = 720;
    private String price = "0";
    private String thumbStr;
    private List<SiteSceneShowInfo.DataBean> beanList;
    private String androidId;

    @Override
    public View getLayout() {
        detailBinding = ActivityTakleCameraFaceDetailBinding.inflate(getLayoutInflater());
        return detailBinding.getRoot();
    }

    @Override
    protected DetailPresenter getPresenter() {
        if (presenter == null) {
            presenter = new DetailPresenter(this, this);
        }
        return presenter;
    }

    @Override
    protected void initEventAndData() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        Glide.with(this).asGif().load(R.drawable.loading).into(detailBinding.ivLoading);
        Intent intent = getIntent();
        pid = intent.getStringExtra("pid");
        presenter.getSiteSceneShow(pid);
        initview();
        initTakleCamera();
        initCountDown();
    }

    private CountDownTimer countDownTimer;
    private void initCountDown() {
        // 设置倒计时 10秒
        countDownTimer = new CountDownTimer(Common.CountDownTime, 1000) { // 10秒倒计时，每1秒更新一次
            @Override
            public void onTick(long millisUntilFinished) {
                // 可以更新UI，显示剩余时间
                // 例如：textView.setText("倒计时：" + millisUntilFinished / 1000);
                detailBinding.tvCountDownTime.setText(""+ millisUntilFinished / 1000);
            }

            @Override
            public void onFinish() {
                // 倒计时结束后退出页面
                finish(); // 关闭当前 Activity
            }
        };
        countDownTimer.start();
    }

    private void initview() {
        detailBinding.glsvMain.setOutlineProvider(new CircleViewOutlineProvider(30));
        detailBinding.glsvMain.setClipToOutline(true);
        detailBinding.ivBtnTable.setOnClickListener(this::onClick);
        detailBinding.ivBtnFace.setOnClickListener(this::onClick);
        detailBinding.ivBack.setOnClickListener(this::onClick);
        detailBinding.ivBtnUpload.setOnClickListener(this::onClick);
        detailBinding.ivBtnChongPai.setOnClickListener(this::onClick);
        detailBinding.rcvList.setLayoutManager(new GridLayoutManager(this, 2));
        detailBinding.rcvList.addItemDecoration(new GridSpacingItemDecoration(2, 20, false));
        detailBinding.clLoading.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
    }

    public static boolean isDestroy(Activity mActivity) {
        if (mActivity == null || mActivity.isFinishing() || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && mActivity.isDestroyed())) {
            return true;
        } else {
            return false;
        }
    }

    private void initTakleCamera() {
        //权限检查
        if (Util.checkPermissionAllGranted(this, mPermissions)) {
            hasPermissions = true;
        } else {
            ActivityCompat.requestPermissions(this, mPermissions, PERMISSION_REQUEST_CODE);
        }
        isPreviewing = false;
        currentCameraId = Camera.CameraInfo.CAMERA_FACING_BACK;  //CAMERA_FACING_BACK
//        currentCameraId = Camera.CameraInfo.CAMERA_FACING_FRONT;
        gpuImage = new GPUImage(this);
        gpuImage.setGLSurfaceView(detailBinding.glsvMain);
        magicFilterGroup = new GPUImageFilterGroup();
        magicFilterGroup.addFilter(new GPUImageBeautyFilter()); //GPUImageBeautyFilter
        noMagicFilterGroup = new GPUImageFilterGroup();
        noMagicFilterGroup.addFilter(new GPUImageMirrorFilter());
        gpuImage.setFilter(magicFilterGroup);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (hasPermissions) {
            startCamera(currentCameraId);
            resume = true;
        }
    }

    // 启用相机
    private void startCamera(int cameraId) {
        try {
            if (camera == null) {
                currentCameraId = cameraId;
                camera = Camera.open(cameraId);
                Camera.Parameters parameters = camera.getParameters();
                parameters.setPictureFormat(PixelFormat.JPEG);

                List<Camera.Size> sizeList = parameters.getSupportedPictureSizes();
                int width = 0;
                int height = 0;

                for (Camera.Size size : sizeList) {
                    if (size.width * size.height <= PICTURE_HEIGHT * PICTURE_WIDTH) {
                        if (size.width * size.height > width * height) {
                            width = size.width;
                            height = size.height;
                        }
                    }
                }
                parameters.setPictureSize(width, height);
                sizeList = parameters.getSupportedPreviewSizes();
                width = 0;
                height = 0;
                for (Camera.Size size : sizeList) {
                    if (size.width * size.height <= PREVIEW_WIDTH * PREVIEW_HEIGHT) {
                        if (size.width * size.height > width * height) {
                            width = size.width;
                            height = size.height;
                        }
                    }
                }
                parameters.setPreviewSize(width, height);
                List<String> stringList = parameters.getSupportedFocusModes();
                for (String s : stringList) {
//                    LogUtil.d(s);
                }
                if (cameraId == 0) {
                    if (stringList.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
                        parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
                    }
                }
                try {
                    camera.setParameters(parameters);
                } catch (RuntimeException e) {
                    Log.e("可见", "Failed to set parameters", e);
                }

                if (!isPreviewing) {
                    isPreviewing = true;
                    gpuImage.setUpCamera(camera, cameraId == 0 ? 0 : 180, cameraId > 0, false);
                }
            }
        } catch (Exception e) {
            showToast("错误" + e.getMessage());
        }
    }

    // 上传人脸
    private void uploadUI(File files) {
        androidId = Settings.System.getString(getContentResolver(), Settings.System.ANDROID_ID);
        // 准备表单参数
        Map<String, String> params = new HashMap<>();
        params.put("back", thumbStr);//thumb
        params.put("price", price);
        params.put("id", pid);
        params.put("address", androidId);
        HttpClient.post01("http://api.datang.qzkaka.com/v1/public/qr-img", params, files, "image/jpeg", QcodeInfo.class, new HttpClient.HttpResponseCallback<QcodeInfo>() {
            @Override
            public void onSuccess(QcodeInfo info) {
                mTipDialog.dismiss();
                detailBinding.clLoading.setVisibility(View.GONE);
                if (info.getCode() == 200) {
                    detailBinding.ivBtnTable.setVisibility(View.GONE);
                    detailBinding.ivBtnUpload.setVisibility(View.GONE);
                    detailBinding.ivBtnChongPai.setVisibility(View.GONE);
                    detailBinding.ivXuniKuan.setVisibility(View.GONE);
                    QcodeInfo.DataBean infoData = info.getData();
//                    qCodeDialog(infoData);
                    // 释放资源
                    clearCamera();
                    if(infoData != null){
                        List<String> dataPhotos = infoData.getPhotos();
                        if (dataPhotos != null && !dataPhotos.isEmpty()){
                            String image = dataPhotos.get(0);
                            Intent mintent = new Intent(DetailCameraFaceTakleActivity.this, ScanCodeActivity.class);
                            mintent.putExtra("url",infoData.getUrl());
                            mintent.putExtra("image",image);
                            startActivity(mintent);
                            finish();
                        }else{
                            startCamera(currentCameraId);
                            detailBinding.ivBtnTable.setVisibility(View.VISIBLE);
                            detailBinding.ivBtnFace.setVisibility(View.GONE);
                            detailBinding.ivBtnChongPai.setVisibility(View.GONE);
                            detailBinding.ivBtnUpload.setVisibility(View.GONE);
                        }
                    }
                } else if (info.getCode() == 422) {
                    showToast(info.getMsg());
                    detailBinding.ivBtnTable.setVisibility(View.VISIBLE);
                    detailBinding.ivBtnFace.setVisibility(View.GONE);
                    detailBinding.ivBtnChongPai.setVisibility(View.GONE);
                    detailBinding.ivBtnUpload.setVisibility(View.GONE);
                    clearCamera();
                    startCamera(currentCameraId);
                }
            }

            @Override
            public void onFailure(String error) {
//                showToast("上传成功");
                showToast("请求超时，请重新拍照");
                detailBinding.clLoading.setVisibility(View.GONE);
                detailBinding.ivBtnTable.setVisibility(View.VISIBLE);
                detailBinding.ivBtnFace.setVisibility(View.GONE);
                detailBinding.ivBtnChongPai.setVisibility(View.GONE);
                detailBinding.ivBtnUpload.setVisibility(View.GONE);
                clearCamera();
                startCamera(currentCameraId);
            }
        });
    }

    private boolean isFace = true;
    // 创建Handler，传递给主线程
    Handler mainHandler = new Handler(Looper.getMainLooper());

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_btn_table:
                detailBinding.ivBtnTable.setVisibility(View.GONE);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        taklePic();
                    }
                }, 1200); // 延迟500毫秒
                break;
            case R.id.iv_btn_chong_pai:
                // 重拍
                detailBinding.ivBtnTable.setVisibility(View.VISIBLE);
                detailBinding.ivBtnFace.setVisibility(View.GONE);
                detailBinding.ivBtnChongPai.setVisibility(View.GONE);
                detailBinding.ivBtnUpload.setVisibility(View.GONE);
                clearCamera();
                startCamera(currentCameraId);
                break;
            case R.id.iv_btn_upload://上传
                detailBinding.clLoading.setVisibility(View.VISIBLE);
                uploadUI(uploadFile);
                break;
            case R.id.iv_btn_face:
                isFace = !isFace;
                gpuImage.setFilter(isFace ? magicFilterGroup : noMagicFilterGroup);
                break;
        }
    }

    // 在这里优化拍照线程的创建
    private ExecutorService executor = Executors.newSingleThreadExecutor();
    private void taklePic(){
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    camera.takePicture(null, null, new Camera.PictureCallback() {
                        @Override
                        public void onPictureTaken(byte[] data, Camera camera) {
                            if (data == null || data.length == 0) {
                                Log.e("CameraCapture", "拍照数据为空");
                                ToastUtils.showShort("拍照数据为空");
                                return;
                            }

                            Bitmap bitmaps = BitmapFactory.decodeByteArray(data, 0, data.length);
                            if (bitmaps == null) {
                                Log.e("CameraCapture", "解码图片失败");
                                ToastUtils.showShort("解码图片失败");
                                return;
                            }

                            Bitmap bitmap = rotateBitmap(bitmaps, 0);
                            if (bitmap == null) {
                                Log.e("CameraCapture", "解码图片失败");
                                return;
                            }
                            // 使用Handler切换到主线程更新UI
                            mainHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    // 在这里更新UI，比如显示图片或更新状态
                                    detailBinding.ivBtnUpload.setVisibility(View.VISIBLE);
                                    detailBinding.ivBtnChongPai.setVisibility(View.VISIBLE);
                                    detailBinding.ivBtnFace.setVisibility(View.GONE);
                                }
                            });
                            int width = bitmap.getWidth();
                            int height = bitmap.getHeight();
                            int xq = width/3;
                            int yq = 0;
                            int xh = width/3;
                            int yh = height;
                            // 检查裁剪区域是否在 Bitmap 范围内
                            if (xq >= 0 && yq >= 0 && xq + xh <= width && yq + yh <= height) {
                                try {
                                    // 创建裁剪的 Bitmap
                                    Bitmap bitmap1 = Bitmap.createBitmap(bitmap, xq, yq, xh, yh);
                                    // 保存裁剪后的图片
                                    uploadFile = saveFile(bitmap1, "pic");
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else {
                                // 如果裁剪区域超出范围，可以处理错误或调整裁剪参数
                                Log.e("BitmapCrop", "裁剪区域超出 Bitmap 范围");
                            }
//                            isCameraInUse = false; // 恢复相机可用状态
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    public File saveFile(Bitmap bm, String fileName) throws IOException {//将Bitmap类型的图片转化成file类型，便于上传到服务器
//        String path = getExternalFilesDir(null) + "/pic.jpg";
        String path = getExternalFilesDir(null).getAbsolutePath();
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        File myCaptureFile = new File(path, fileName);//+ fileName
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 70, bos);
        bos.flush();
        bos.close();
        return myCaptureFile;

    }

    /**
     * 将图片按照某个角度进行旋转
     *
     * @param bm     需要旋转的图片
     * @param degree 旋转角度
     * @return 旋转后的图片
     */
    private Bitmap rotateBitmap(Bitmap bm, int degree) {
        Bitmap returnBm = null;
        // 根据旋转角度，生成旋转矩阵
        Matrix matrix = new Matrix();
        matrix.postRotate(degree);
        try {
            // 将原始图片按照旋转矩阵进行旋转，并得到新的图片
            returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
                    bm.getHeight(), matrix, true);
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
        }
        if (returnBm == null) {
            returnBm = bm;
        }
        if (bm != returnBm) {
            bm.recycle();
        }
        return returnBm;
    }

    @Override
    public void onFailer(Throwable throwable) {

    }

    @Override
    public void onSiteDetail(SiteDetailInfo info) {

    }

    @Override
    public void onUpload(UploadImgInfo info) {
        switch (info.getStatus()) {
            case 200:
                UploadImgInfo.DataBean infoData = info.getData();
                if (infoData != null) {
                    String thumb = infoData.getThumb();
                    showToast(thumb);
                }
                break;
            case 422:
                showToast(info.getMessage());
                break;
        }
    }

    /**
     * 风格背景图
     *
     * @param info
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onSiteSceneShow(SiteSceneShowInfo info) {
        switch (info.getStatus()) {
            case 200:
                price = info.getPrice();
                beanList = info.getData();
                // 以逗号拼接
                thumbStr = beanList.stream()
                        .map(SiteSceneShowInfo.DataBean::getThumb)  // 提取thumb字段
                        .collect(Collectors.joining(","));
                Log.e("拼接结果", thumbStr);
                //刷新数据之后，需要重新设置是否支持自动轮播
                FengGeSceneAdapter teachDataAdapter = new FengGeSceneAdapter(R.layout.item_fengge_scene, beanList);
                detailBinding.rcvList.setAdapter(teachDataAdapter);
                teachDataAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        teachDataAdapter.choicePostion(position);
                        teachDataAdapter.notifyDataSetChanged();
                        List<SiteSceneShowInfo.DataBean> dataBeanList = teachDataAdapter.getData();
                        if(dataBeanList != null && dataBeanList.size() != 0){
                            SiteSceneShowInfo.DataBean dataBean = dataBeanList.get(position);
                            if(dataBean != null){
                                loadImageIntoImageView(detailBinding.rivImageYu, dataBean.getThumb());
                            }
                        }
                    }
                });

                if (!beanList.isEmpty()) {
                    SiteSceneShowInfo.DataBean dataBean = beanList.get(0);
                    if (dataBean != null) {
                        loadImageIntoImageView(detailBinding.rivImageYu, dataBean.getThumb());
                    }
                }else{

                }
                break;
            case 422:
                showToast(info.getMessage());
                break;
        }
    }

    private void loadImageIntoImageView(ImageView imageView, String imageUrl) {
        if (!isDestroy(DetailCameraFaceTakleActivity.this)) {
            Glide.with(this)
                    .load(imageUrl)
                    .into(imageView);
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        clearCamera();
    }

    private void clearCamera() {
        if (camera != null) {
            gpuImage.deleteImage();
            camera.setPreviewCallback(null);
            camera.stopPreview();
            isPreviewing = false;
            camera.release();
            camera = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        clearCamera();
        if (countDownTimer != null) {
            countDownTimer.cancel(); // 确保倒计时被取消
        }
    }

    /**
     * 申请权限结果返回处理
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            boolean isAllGranted = true;
            for (int grant : grantResults) {  // 判断是否所有的权限都已经授予了
                if (grant != PackageManager.PERMISSION_GRANTED) {
                    isAllGranted = false;
                    break;
                }
            }
            if (isAllGranted) { // 所有的权限都授予了
                startCamera(currentCameraId);
            } else {// 提示需要权限的原因
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setMessage("拍照需要允许权限, 是否再次开启?")
                        .setTitle("提示")
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ActivityCompat.requestPermissions(DetailCameraFaceTakleActivity.this, mPermissions, PERMISSION_REQUEST_CODE);
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                finish();
                            }
                        });
                builder.create().show();
            }
        }
    }



}
